import { notFound } from 'next/navigation'
import { Metadata } from 'next'
import { getTools } from '@/lib/database'
import { ToolDetailWrapper } from '@/components/tools/tool-detail-wrapper'
import { ToolAccessButton } from '@/components/tools/tool-access-button'
import { FavoriteButton } from '@/components/favorites/favorite-button'
import { Calendar, User, Tag } from 'lucide-react'
import Link from 'next/link'

// 强制动态渲染，因为需要请求上下文来生成正确的URL
export const dynamic = 'force-dynamic'

interface ToolPageProps {
  params: Promise<{
    id: string
  }>
}

// 生成静态参数
export async function generateStaticParams() {
  try {
    const tools = await getTools()
    return tools.map((tool) => ({
      id: tool.id,
    }))
  } catch (error) {
    console.error('Error generating static params:', error)
    return []
  }
}

// 生成元数据
export async function generateMetadata({ params }: ToolPageProps): Promise<Metadata> {
  const { id } = await params

  try {
    const tools = await getTools()
    const tool = tools.find(t => t.id === id)

    if (!tool) {
      return {
        title: '工具未找到',
        description: '您访问的工具不存在'
      }
    }

    return {
      title: `${tool.title} - 工具聚合`,
      description: tool.description,
      openGraph: {
        title: tool.title,
        description: tool.description,
        images: tool.image ? [tool.image] : [],
      },
    }
  } catch (error) {
    return {
      title: '工具详情',
      description: '查看工具详细信息'
    }
  }
}

export default async function ToolPage({ params }: ToolPageProps) {
  const { id } = await params

  // 获取工具信息
  const tools = await getTools()
  const tool = tools.find(t => t.id === id)

  if (!tool) {
    notFound()
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* 工具基本信息 */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
          <div className="flex items-start justify-between mb-4">
            <div className="flex-1">
              <h1 className="text-3xl font-bold text-gray-900 mb-2">{tool.title}</h1>
              <p className="text-gray-600 text-lg leading-relaxed mb-4">
                {tool.description}
              </p>

              {/* 工具元信息 */}
              <div className="flex flex-wrap items-center gap-4 text-sm text-gray-500">
                <div className="flex items-center gap-1">
                  <Tag className="h-4 w-4" />
                  <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                    {tool.category.icon} {tool.category.name}
                  </span>
                </div>
                <div className="flex items-center gap-1">
                  <User className="h-4 w-4" />
                  <span>发布者: {tool.user.name}</span>
                </div>
                <div className="flex items-center gap-1">
                  <Calendar className="h-4 w-4" />
                  <span>发布时间: {new Date(tool.createdAt).toLocaleDateString()}</span>
                </div>
              </div>
            </div>

            {/* 操作按钮 */}
            <div className="flex items-center gap-3 ml-6">
              <FavoriteButton toolId={id} />
              <ToolAccessButton tool={tool} />
            </div>
          </div>

          {/* 工具预览（仅对已部署的工具显示） */}
          {tool.isDeployed && (
            <div className="border border-gray-200 rounded-lg overflow-hidden">
              <div className="bg-gray-100 px-4 py-2 border-b border-gray-200">
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium text-gray-700">工具预览</span>
                  <div className="flex gap-2">
                    <Link
                      href={`/tools/deployed/${id}?minimal=true`}
                      className="text-xs text-blue-600 hover:text-blue-700"
                    >
                      极简模式
                    </Link>
                    <Link
                      href={`/tools/deployed/${id}`}
                      className="text-xs text-blue-600 hover:text-blue-700"
                    >
                      完整页面
                    </Link>
                  </div>
                </div>
              </div>
              <div className="h-96">
                <iframe
                  src={`/deployed-tools/${id}/index.html`}
                  className="w-full h-full border-0"
                  title={tool.title}
                  sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
                />
              </div>
            </div>
          )}
        </div>

        {/* 评价部分 */}
        <ToolDetailWrapper toolId={id} />

        {/* 返回按钮 */}
        <div className="mt-8 text-center">
          <Link
            href="/"
            className="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
          >
            ← 返回首页
          </Link>
        </div>
      </div>
    </div>
  )
}
